package com.transcargo.request;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.transcargo.action.ServletParametersException;
import com.transcargo.action.ServletValidationException;
import com.transcargo.db.db;
import com.transcargo.db.dbException;
import com.transcargo.rpc.RPCOutput;

public class ContinueSearchRequest extends SearchRequest {
    private String override = "";


    private void servletGetValues(HttpServletRequest request) throws ServletParametersException, ServletException {
        hash = request.getParameter("hash");
        sfrom = request.getParameter("sfrom");
        override = request.getParameter("override");
        if (hash == null || hash.length() != 12) throw new ServletParametersException();
        if (sfrom == null || sfrom.length() == 0) sfrom="0";
    }

    private void servletValidateValues() throws ServletValidationException {
    }

    private void servletExecuteRequest() throws ServletRequestException {
        db.PreStatement pre;
        try {
            pre = dbase.CreateStatement("SELECT date, type, convert(UNHEX(query) using utf8), count FROM hashedqueries WHERE hash=?");
            pre.Insert(hash);
            list = dbase.execute(pre);
            if (list != null) {
                iter = list.iterator();
                if (!iter.hasNext()) {
                    System.out.println("Error, invalid query, returned no results, hash=" + hash);
                    xml = RPCOutput.generate(false);     // something wrong happen, shouldn't get here
                    return;
                }
                String[] res = iter.next();
                if (res[1].equals("0")) {
                    if (override == null) {
                        resultCount = Integer.parseInt(res[3]);
                        String statementPrefix = "SELECT count(id) FROM posted_transport WHERE " + res[2] + " AND date_posted<='" + res[0]+"'";
                        list = dbase.execute(statementPrefix);
                        iter = list.iterator();
                        String[] cnt = iter.next();
                        if (Integer.parseInt(cnt[0]) == resultCount) {
                            statementPrefix = "SELECT count(id) FROM posted_transport WHERE " + res[2] + " AND date_posted>'" + res[0]+"'";
                            list = dbase.execute(statementPrefix);
                            iter = list.iterator();
                            cnt = iter.next();
                            if (cnt[0].equals("0")) {
                                xml = RPCOutput.generate(true,"hash",hash);
                                return;
                            }
                        }
                    }
                    xml = doSearchFreight(res[2]);
                    pre = dbase.CreateStatement("UPDATE hashedqueries SET date=CURRENT_TIMESTAMP,count=? WHERE hash=?");
                    pre.Insert(resultCount);
                    pre.Insert(hash);
                    dbase.executeUpdate(pre);
                } else {
                    if (override == null) {
                        resultCount = Integer.parseInt(res[3]);
                        String statementPrefix = "SELECT count(id) FROM posted_cargo WHERE " + res[2] + " AND date_posted<='" + res[0]+"'";
                        list = dbase.execute(statementPrefix);
                        iter = list.iterator();
                        String[] cnt = iter.next();
                        if (Integer.parseInt(cnt[0]) == resultCount) {
                            statementPrefix = "SELECT count(id) FROM posted_cargo WHERE " + res[2] + " AND date_posted>'" + res[0]+"'";
                            list = dbase.execute(statementPrefix);
                            iter = list.iterator();
                            cnt = iter.next();
                            if (cnt[0].equals("0")) {
                                xml = RPCOutput.generate(true);
                                return;
                            }
                        }
                    }
                    xml = doSearchCargo(res[2]);
                    pre = dbase.CreateStatement("UPDATE hashedqueries SET date=CURRENT_TIMESTAMP,count=? WHERE hash=?");
                    pre.Insert(resultCount);
                    pre.Insert(hash);
                    dbase.executeUpdate(pre);
                }
            }
        } catch (SQLException e) {
            System.out.println("SQLException during search: " + e.getMessage());
            throw new ServletRequestException();
        } catch (dbException e) {
            System.out.println("DB Exception during search: " + e.getMessage());
            throw new ServletRequestException();
        }
    }
    public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        PrintWriter out = null;
		try {
            out = response.getWriter();

            servletGetValues(request);
            servletValidateValues();
            servletExecuteRequest();
            out.println(xml);
	    } catch (ServletParametersException e) {
           sendRedirect(response, "index.jsp");
        }  catch (ServletValidationException e) {
            sendError(response, new Exception(e.getMessage()));
        }  catch (ServletRequestException e) {
            String xml =  RPCOutput.generate(false);
            out.println(xml);
        }  catch (IOException e) {
            System.out.println("IOException: " + e.getMessage());
        }
    }
}
